package com.jic.purchase.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jic.common.base.vo.PageResult;
import com.jic.purchase.constant.consist.ResponseCode;
import com.jic.purchase.exception.AppRuntimeException;
import com.jic.purchase.mapper.SupplierBusinessLicenseMapper;
import com.jic.purchase.mapper.SupplierInformationMapper;
import com.jic.purchase.model.entity.SupplierBusinessLicense;
import com.jic.purchase.model.entity.SupplierFinancialInformation;
import com.jic.purchase.model.entity.SupplierInformation;
import com.jic.purchase.model.entity.SupplierShippingAddressInformation;
import com.jic.purchase.model.vo.request.SupplierInformationRequest;
import com.jic.purchase.model.vo.request.SuppliersSettledInRequest;
import com.jic.purchase.model.vo.response.SupplierBusinessLicenseResponse;
import com.jic.purchase.model.vo.response.SupplierFinancialInformationResponse;
import com.jic.purchase.model.vo.response.SupplierInformationResponse;
import com.jic.purchase.model.vo.response.SupplierShippingAddressInformationResponse;
import com.jic.purchase.service.SupplierBusinessLicenseService;
import com.jic.purchase.service.SupplierFinancialInformationService;
import com.jic.purchase.service.SupplierInformationService;
import com.jic.purchase.service.SupplierShippingAddressInformationService;
import com.jic.purchase.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class SupplierInformationServiceImpl implements SupplierInformationService {

	@Resource
	private SupplierInformationMapper mapper;

	@Resource
	private SupplierBusinessLicenseMapper businessLicenseMapper;

	@Resource
	private SupplierBusinessLicenseService supplierBusinessLicenseService;

	@Resource
	private SupplierFinancialInformationService supplierFinancialInformationService;

	@Resource
	private SupplierShippingAddressInformationService supplierShippingAddressInformationService;


	/**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(SupplierInformation request) {
	 int flag = mapper.insert(request);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author 建投数据科技(山东)有限公司
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public Long saveOrUpdate(SupplierInformationRequest request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		SupplierInformation supplierInformation = new SupplierInformation();
		BeanUtils.copyProperties(request, supplierInformation);
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				int flag = mapper.updateByPrimaryKey(supplierInformation);
				//更新或新增营业执照信息
				if (request.getBusinessLicenseInfo() != null){
					SupplierBusinessLicense supplierBusinessLicense = new SupplierBusinessLicense();
					BeanUtils.copyProperties(request.getBusinessLicenseInfo(), supplierBusinessLicense);
					supplierBusinessLicenseService.saveOrUpdate(supplierBusinessLicense);
				}
				//更新或新增财务信息
				if (request.getFinancialInformationInfo() != null){
					SupplierFinancialInformation financialInformation = new SupplierFinancialInformation();
					BeanUtils.copyProperties(request.getFinancialInformationInfo(), financialInformation);
					supplierFinancialInformationService.saveOrUpdate(financialInformation);
				}
				//更新或新增发货地址信息
				if (request.getShipAddres() != null){
					SupplierShippingAddressInformation shippAddress = new SupplierShippingAddressInformation();
					BeanUtils.copyProperties(request.getShipAddres(), shippAddress);
					supplierShippingAddressInformationService.saveOrUpdate(shippAddress);

				}
				if(flag == 1){
				  return supplierInformation.getId();
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(supplierInformation));
                supplierInformation.setCreateTime(new Date());
				int flag = mapper.insertSelective(supplierInformation);
				if(flag == 1){
				  return supplierInformation.getId();
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return supplierInformation.getId();
	}

	/**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(SupplierInformation request) {
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(SupplierInformation request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(SupplierInformation request){
		try {
			log.info("修改记录");
			SupplierInformation param = new SupplierInformation();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public SupplierInformationResponse getByPrimaryKey(SupplierInformation request) {
		//获取供应商基本信息
		SupplierInformation result = mapper.selectByPrimaryKey(request);
		SupplierInformationResponse bo = new SupplierInformationResponse();
		if (request != null){
			BeanUtils.copyProperties(result, bo);
			SupplierBusinessLicense businessLicense = new SupplierBusinessLicense();
			businessLicense.setSupplierId(result.getId());
			//查询供应商营业执照信息
			SupplierBusinessLicense businessLicenseResult = supplierBusinessLicenseService.getBySupplierId(businessLicense);
			if (businessLicenseResult != null){
				SupplierBusinessLicenseResponse businessLicenseResponse = new SupplierBusinessLicenseResponse();
				BeanUtils.copyProperties(businessLicenseResult, businessLicenseResponse);
				bo.setBusinessLicenseInfo(businessLicenseResponse);
			}
			//查询供应商财务信息
			SupplierFinancialInformation financialInformation = new SupplierFinancialInformation();
			financialInformation.setSupplierId(request.getId());
			SupplierFinancialInformation financialInformationResult = supplierFinancialInformationService.getBySupplierId(financialInformation);
			if (financialInformationResult != null){
				SupplierFinancialInformationResponse financialInformationResponse = new SupplierFinancialInformationResponse();
				BeanUtils.copyProperties(financialInformationResult, financialInformationResponse);
				bo.setFinancialInformationInfo(financialInformationResponse);
			}

			//查询供应商发货地址信息
			SupplierShippingAddressInformation shipAddresRequest = new SupplierShippingAddressInformation();
			shipAddresRequest.setSupplierId(result.getId());
			SupplierShippingAddressInformation shipAddresResponse = supplierShippingAddressInformationService.getBySupplierId(shipAddresRequest);
			if (shipAddresResponse != null){
				SupplierShippingAddressInformationResponse shipAddressResult = new SupplierShippingAddressInformationResponse();
				BeanUtils.copyProperties(shipAddresResponse, shipAddressResult);
				bo.setShipAddress(shipAddressResult);
			}
		}
		return bo;
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageResult<SupplierInformationResponse> listPageBySelective(SupplierInformation request, int pageNum, int pageSize) {
		Page<SupplierInformationResponse> page = PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy(" create_time desc");
//		Long count = mapper.listPageBySelectiveCount(request);
		List<SupplierInformationResponse> responseList = mapper.querySupplierListPage(request);
		PageResult<SupplierInformationResponse> result = new PageResult<>();
		result.setTotal(page.getTotal());
		result.setRows(responseList);
		return  result;
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<SupplierInformation> listAllRecord(SupplierInformation request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public int suppliersSettledIn(SuppliersSettledInRequest request) {
		SupplierInformation param = new SupplierInformation();
		BeanUtils.copyProperties(request, param);
		param.setSource(2);//来源为入驻
		param.setStatus(3);//状态默认为待审核
		mapper.insert(param);
		SupplierBusinessLicense businessLicense = BeanUtil.copy(request.getBusinessLicense(), SupplierBusinessLicense.class);
		businessLicense.setSupplierId(param.getId());
		int flag = businessLicenseMapper.insert(businessLicense);
		return flag;
	}

	@Override
	public List<SupplierInformationResponse> querySupplierInfoList(SupplierInformationRequest request) {
		if (request == null){
			log.error("querySupplierInfoList param is null");
			return Lists.newArrayList();
		}
		List<SupplierInformation> supplierInformations = mapper.querySupplierInfoList(request);
		if (CollectionUtils.isNotEmpty(supplierInformations)){
			List<SupplierInformationResponse> responseList = supplierInformations.stream().map(temp -> {
				SupplierInformationResponse bo = new SupplierInformationResponse();
				BeanUtils.copyProperties(temp, bo);
				return bo;
			}).filter(item -> item != null).collect(Collectors.toList());
			return responseList;
		}
		return Lists.newArrayList();
	}


}
